package org.jeecg.modules.system.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.model.WorkHourBaseVo;
import org.jeecg.modules.system.model.WorkHourVo;
import org.jeecg.modules.system.service.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: sys_user_report
 * @Author: jeecg-boot
 * @Date: 2022-10-06
 * @Version: V1.0
 */
@Api(tags = "工作日志接口")
@RestController
@RequestMapping("/sysUserReport")
@Slf4j
public class SysUserReportController extends JeecgController<SysUserReport, ISysUserReportService> {
    @Autowired
    private ISysUserReportService sysUserReportService;
    @Autowired
    private SysUserController sysUserController;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysUserDepartService sysUserDepartService;
    @Autowired
    private ISysDepartService sysDepartService;
    /**
     * 列表查询
     *
     * @return
     */
//    @ApiOperation(value = "工作日志列表查询", notes = "工作日志分页列表查询")
    @GetMapping(value = "/list")
    public Result<List<SysUserReport>> queryList(@RequestParam(name="date",required = false) String date,
                                                 @RequestParam(value = "userId",required = false) String userId,
                                                 @RequestParam(value = "limit",required = false) Integer limit
    ) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.isEmpty(userId)){
            userId = sysUser.getId();
        }
        List<SysUserReport> pageList = sysUserReportService.queryList(date, userId,limit);
        return Result.OK(pageList);
    }


    @ApiOperation(value = "工作日志分页列表查询", notes = "工作日志分页列表查询")
    @GetMapping(value = "/page")
    public Result<Page<SysUserReport>> queryList(
            @RequestParam(name = "date", required = false) String date,
            @RequestParam(name = "date_begin", required = false) String dateBegin,
            @RequestParam(name = "date_end", required = false) String dateEnd,
            @RequestParam(value = "userId", required = false) String userId,
            @RequestParam(value = "strength", required = false) String strength,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.isEmpty(userId)){
            userId = sysUser.getId();
        }
        Page<SysUserReport> page = new Page<SysUserReport>(pageNo, pageSize);

//        Page<SysUserReport> pageList = sysUserReportService.queryPage(page,date, userId);
        Page<SysUserReport> pageList = sysUserReportService.queryPage(page,dateBegin,dateEnd, userId,strength);
        return Result.OK(pageList);
    }


    /**
     * 列表查询
     *
     * @return
     */
    @ApiOperation(value = "工时概要接口", notes = "工时")
    @GetMapping(value = "/workHour")
    public Result<WorkHourBaseVo> workHour(@RequestParam(value = "userId",required = false) String userId,
                                           @RequestParam(value = "standard",required = false) Integer standard) {
        WorkHourBaseVo res = new WorkHourBaseVo();
        SysUser parenUser = null;
        if(StringUtils.isEmpty(userId)){
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userId = sysUser.getId();
        }
        SysUser currentUser = userService.getById(userId);
        parenUser = userService.getByName(currentUser.getCreateBy());
        if (null!=parenUser){
            res.setParentName(parenUser.getRealname());
            res.setParentTel(parenUser.getPhone());
        }

        Integer remainHour = userService.getById(userId).getRemainingWork();//剩余时间
        res.setWorkHourRemain(null==remainHour?0:remainHour/24);
        SysRole role = sysUserRoleService.getUserRole(userId);

        String date = LocalDate.now().toString();
        Integer workHour = sysUserReportService.workHour(date, role.getRoleCode(), userId);
        String a = "0小时";
        if (workHour != null && workHour > 0) {
            int hour = workHour / 60;
            int min = workHour % 60;
            if (hour == 0 ) {
                a= min + "分钟" ;
            } else {
                a=  hour + "小时" + min + "分钟" ;
            }
        }

        res.setWorkTime(a);

        Integer workMinutesDay = userService.getWorkTimeByUserId(role.getRoleCode(),userId,"1",null);
        res.setWorkTimeDay(sysUserController.groupWorkTime(workMinutesDay));
        Integer workMinutesWeek = userService.getWorkTimeByUserId(role.getRoleCode(),userId,"2",null);
        res.setWorkTimeWeek(sysUserController.groupWorkTime(workMinutesWeek));
        Integer workMinutesMonth = userService.getWorkTimeByUserId(role.getRoleCode(),userId,"3",null);
        res.setWorkTimeMonth(sysUserController.groupWorkTime(workMinutesMonth));
        Integer workMinutesTotal = userService.getWorkTimeByUserId(role.getRoleCode(),userId, "", null);
        res.setWorkTimeTotal(sysUserController.groupWorkTime(workMinutesTotal));

//        Integer workMinutesDayPass = userService.getWorkTimeByUserId(role.getRoleCode(),userId, "1", standard);
//        res.setWorkTimeDayPass(sysUserController.groupWorkTime(workMinutesDayPass));
//        Integer workMinutesWeekPass = userService.getWorkTimeByUserId(role.getRoleCode(),userId, "2", standard);
//        res.setWorkTimeWeekPass(sysUserController.groupWorkTime(workMinutesWeekPass));
//        Integer workMinutesMonthPass = userService.getWorkTimeByUserId(role.getRoleCode(),userId, "3", standard);
//        res.setWorkTimeMonthPass(sysUserController.groupWorkTime(workMinutesMonthPass));
//        Integer workMinutesTotalPass = userService.getWorkTimeByUserId(role.getRoleCode(),userId, "", standard);
//        res.setWorkTimeTotalPass(sysUserController.groupWorkTime(workMinutesTotalPass));



        res.setWorkDayDay(userService.getWorkDayByUserId(role.getRoleCode(),"2",userId,"1"));
        res.setWorkDayWeek(userService.getWorkDayByUserId(role.getRoleCode(),"2",userId,"2"));
        res.setWorkDayMonth(userService.getWorkDayByUserId(role.getRoleCode(),"2",userId,"3"));
        res.setWorkDayTotal(userService.getWorkDayByUserId(role.getRoleCode(),"2",userId,""));


//        if (workMinutesDayPass>0)
//            res.setWorkTimeDayPassRate((100*workMinutesDayPass)/workMinutesDay);
//        if (workMinutesWeekPass>0)
//            res.setWorkTimeWeekPassRate((100*workMinutesWeekPass)/workMinutesWeek);
//        if (workMinutesMonthPass>0)
//            res.setWorkTimeMonthPassRate((100*workMinutesMonthPass)/workMinutesMonth);
//        if (workMinutesTotalPass>0)
//            res.setWorkTimeTotalPassRate((100*workMinutesTotalPass)/workMinutesTotal);

        return Result.OK(res);
    }
    
    private void getCompany(String userId, List<String> depts) {
        LambdaQueryWrapper<SysUserDepart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserDepart::getUserId, userId);
        List<SysUserDepart> list = sysUserDepartService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
            query.eq(SysDepart::getParentId, list.get(0).getDepId());
            List<SysDepart> departList = sysDepartService.list(query);
            if (!CollectionUtils.isEmpty(departList)) {
                depts.addAll(departList.stream().map(SysDepart::getId).collect(Collectors.toList()));
            }
        }
    }
    
    @ApiOperation(value = "工时图表查询", notes = "工时")
    @GetMapping(value = "/workHourChar")
    public Result<List<WorkHourVo>> workHourChar(@RequestParam(value = "userId",required = false) String userId) {
        if(StringUtils.isEmpty(userId)){
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userId = sysUser.getId();
        }
        SysRole role = sysUserRoleService.getUserRole(userId);
        List<String> depts = new ArrayList<>();
        if (role != null) {
            String roleId = role.getRoleCode();
            if ("distributor".equals(roleId)) {
                getDistributor(userId, depts);
            } else if ("company".equals(roleId)) {
                getCompany(userId, depts);
            }
        }
        depts = !CollectionUtils.isEmpty(depts) ? depts : Arrays.asList("asdasd");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        String date = LocalDate.now().format(formatter);
        List<WorkHourVo> list = sysUserReportService.workHourChar(date, role.getRoleCode(), userId, depts);
        return Result.OK(list);
    }
    
    private void getDistributor(String userId, List<String> depts) {
        LambdaQueryWrapper<SysUserDepart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserDepart::getUserId, userId);
        List<SysUserDepart> list = sysUserDepartService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<>();
            query.eq(SysDepart::getParentId, list.get(0).getDepId());
            List<SysDepart> departList = sysDepartService.list(query);
            if (!CollectionUtils.isEmpty(departList)) {
                query = new LambdaQueryWrapper<>();
                query.in(SysDepart::getParentId, departList.stream().map(SysDepart::getId).collect(Collectors.toList()));
                departList = sysDepartService.list(query);
                if (!CollectionUtils.isEmpty(departList)) {
                    depts.addAll(departList.stream().map(SysDepart::getId).collect(Collectors.toList()));
                }
            }
        }
    }
    
    
    /**
     * 添加
     *
     * @param sysUserReport
     * @return
     */
    @AutoLog(value = "工作日志添加")
//    @ApiOperation(value = "工作日志添加", notes = "工作日志添加")
    //@RequiresPermissions("org.jeecg.modules.demo:sys_user_report:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SysUserReport sysUserReport) {
        sysUserReportService.save(sysUserReport);
        return Result.OK("添加成功！");
    }
    
    /**
     * 编辑
     *
     * @param sysUserReport
     * @return
     */
    @AutoLog(value = "工作日志编辑")
//    @ApiOperation(value = "工作日志编辑", notes = "工作日志编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:sys_user_report:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SysUserReport sysUserReport) {
        sysUserReportService.updateById(sysUserReport);
        return Result.OK("编辑成功!");
    }
    
    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工作日志通过id删除")
//    @ApiOperation(value = "工作日志通过id删除", notes = "工作日志通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:sys_user_report:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        sysUserReportService.removeById(id);
        return Result.OK("删除成功!");
    }
    
    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "工作日志批量删除")
//    @ApiOperation(value = "工作日志批量删除", notes = "工作日志批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:sys_user_report:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysUserReportService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }
    
    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "工作日志通过id查询")
//    @ApiOperation(value = "工作日志通过id查询", notes = "工作日志通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SysUserReport> queryById(@RequestParam(name = "id", required = true) String id) {
        SysUserReport sysUserReport = sysUserReportService.getById(id);
        if (sysUserReport == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sysUserReport);
    }
    
    /**
     * 导出excel
     *
     * @param request
     * @param sysUserReport
     */
    //@RequiresPermissions("org.jeecg.modules.demo:sys_user_report:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysUserReport sysUserReport) {
        return super.exportXls(request, sysUserReport, SysUserReport.class, "sys_user_report");
    }
    
    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("sys_user_report:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysUserReport.class);
    }
    
}
